<template>
  <div class="page-wrap">
    <div class="page-header">
      <div class="page-title">
        调拨管理
        <el-tag type="info" effect="plain" class="title-tag">Transfer Management</el-tag>
      </div>
      <div class="page-actions">
        <el-button type="primary" @click="handleAdd">新增调拨</el-button>
        <el-button @click="handleReset" :loading="loading" plain>重置</el-button>
        <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
        <el-button type="success" @click="exportCsv" :disabled="!tableData.length">导出 CSV</el-button>
      </div>
    </div>

    <el-card class="search-card" shadow="never">
      <el-form :inline="true" label-width="100px" @submit.prevent>
        <el-form-item label="调拨单号">
          <el-input
            v-model="query.TransferNo"
            placeholder="模糊搜索调拨单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="调出仓库">
          <el-select
            v-model="query.FromWarehouseId"
            placeholder="选择调出仓库"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调入仓库">
          <el-select
            v-model="query.ToWarehouseId"
            placeholder="选择调入仓库"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
            v-model="query.BillStatus"
            placeholder="选择单据状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" :value="10" />
            <el-option label="待出库" :value="30" />
            <el-option label="待入库" :value="60" />
            <el-option label="已完成" :value="100" />
            <el-option label="驳回" :value="90" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库状态">
          <el-select
            v-model="query.OutStatus"
            placeholder="选择出库状态"
            clearable
            style="width: 150px"
          >
            <el-option label="未出库" :value="0" />
            <el-option label="部分出库" :value="1" />
            <el-option label="已出库" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="入库状态">
          <el-select
            v-model="query.InStatus"
            placeholder="选择入库状态"
            clearable
            style="width: 150px"
          >
            <el-option label="未入库" :value="0" />
            <el-option label="部分入库" :value="1" />
            <el-option label="已入库" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="query.BeginDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 160px"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="query.EndDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 160px"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <div class="stats-row">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-title">记录数</div>
        <div class="stat-value">{{ total }}</div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-title">总调拨数量</div>
        <div class="stat-value">{{ formatNumber(sumQuantity) }}</div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-title">总调拨金额</div>
        <div class="stat-value">{{ formatNumber(sumAmount) }}</div>
      </el-card>
    </div>

    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" border stripe height="520" :header-cell-style="{background:'#f7f9fc'}">
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="transferNo" label="调拨单号" min-width="160" />
        <el-table-column prop="applyDate" label="申请日期" width="120">
          <template #default="{ row }">{{ formatDate(row.applyDate) }}</template>
        </el-table-column>
        <el-table-column prop="transferType" label="调拨类型" width="120" />
        <el-table-column prop="fromWarehouseName" label="调出仓库" min-width="140" />
        <el-table-column prop="toWarehouseName" label="调入仓库" min-width="140" />
        <el-table-column prop="billStatusName" label="单据状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.billStatus)" size="small">
              {{ row.billStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="outStatusName" label="出库状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getOutStatusType(row.outStatus)" size="small">
              {{ row.outStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inStatusName" label="入库状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getInStatusType(row.inStatus)" size="small">
              {{ row.inStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalQty" label="总数量" width="100" align="right">
          <template #default="{ row }">{{ formatNumber(row.totalQty) }}</template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
          <template #default="{ row }">{{ formatNumber(row.totalAmount) }}</template>
        </el-table-column>
        <el-table-column prop="handlerName" label="经办人" width="100" />
        <el-table-column prop="applicantName" label="申请人" width="100" />
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" text @click="openDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="query.PageIndex"
          :page-size="query.PageSize"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { ReadClients, WriteClients } from '../../Urls/AxiosHelper'
import { useRouter } from 'vue-router'

const router = useRouter()

const Read = ReadClients[0]
const Write = WriteClients[0]

interface TransferItem {
  transferId: number
  transferNo: string
  applyDate: string
  transferType: string
  fromWarehouseId: number
  fromWarehouseName: string
  toWarehouseId: number
  toWarehouseName: string
  billStatus: number
  billStatusName: string
  outStatus: number
  outStatusName: string
  inStatus: number
  inStatusName: string
  totalQty: number
  totalAmount: number
  handlerName: string
  applicantName: string
  createdAt: string
  updatedAt: string
}

interface ApiResponse<T> {
  code: number
  message: string
  data: {
    totalCount: number
    totalPage: number
    data: T[]
  }
}

interface Warehouse {
  id: number
  name: string
}

const loading = ref(false)
const tableData = ref<TransferItem[]>([])
const total = ref(0)
const warehouses = ref<Warehouse[]>([])

const query = reactive({
  PageIndex: 1,
  PageSize: 10,
  TransferNo: '',
  FromWarehouseId: undefined as number | undefined,
  ToWarehouseId: undefined as number | undefined,
  BillStatus: undefined as number | undefined,
  OutStatus: undefined as number | undefined,
  InStatus: undefined as number | undefined,
  BeginDate: '',
  EndDate: ''
})

// 计算统计信息
const sumQuantity = computed(() => tableData.value.reduce((s, x) => s + (Number(x.totalQty) || 0), 0))
const sumAmount = computed(() => tableData.value.reduce((s, x) => s + (Number(x.totalAmount) || 0), 0))

// 获取调拨列表
async function fetchList() {
  loading.value = true
  try {
    const params: any = {
      pageIndex: query.PageIndex,
      pageSize: query.PageSize
    }
    
    // 根据API文档正确映射参数
    if (query.TransferNo) params.transferId = query.TransferNo
    if (query.FromWarehouseId) params.fromWarehouseId = query.FromWarehouseId
    if (query.ToWarehouseId) params.toWarehouseId = query.ToWarehouseId
    if (query.BillStatus !== undefined) params.billStatus = query.BillStatus
    if (query.OutStatus !== undefined) params.outStatus = query.OutStatus
    if (query.InStatus !== undefined) params.inStatus = query.InStatus
    if (query.BeginDate) params.beginDate = query.BeginDate
    if (query.EndDate) params.endDate = query.EndDate

    console.log('发送的查询参数:', params)
    console.log('原始查询对象:', query)

    // 使用正确的API路径（根据Swagger文档）
    const res = await Read.get<ApiResponse<TransferItem>>('/wareread/api/AllocationQuery/GetTransferList', { params })
    const payload = res.data
    
    if (payload.code !== 200) {
      throw new Error(payload.message || '请求失败')
    }
    
    tableData.value = payload.data?.data || []
    total.value = payload.data?.totalCount || 0
  } catch (err: any) {
    ElMessage.error(err?.message || '加载失败')
  } finally {
    loading.value = false
  }
}


// 获取仓库列表（模拟数据）
async function fetchWarehouses() {
  // 这里应该调用实际的仓库API，暂时使用模拟数据
  warehouses.value = [
    { id: 1, name: '成品仓库一' },
    { id: 2, name: '成品仓库二' },
    { id: 3, name: '原料仓库一' },
    { id: 4, name: '原料仓库二' }
  ]
}

// 状态类型映射
function getStatusType(status: number) {
  switch (status) {
    case 10: return 'warning'
    case 30: return 'info'
    case 60: return 'primary'
    case 100: return 'success'
    case 90: return 'danger'
    default: return 'info'
  }
}

function getOutStatusType(status: number) {
  switch (status) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return 'success'
    default: return 'info'
  }
}

function getInStatusType(status: number) {
  switch (status) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return 'success'
    default: return 'info'
  }
}

// 格式化函数
function formatNumber(n: number | string) {
  const num = Number(n ?? 0)
  return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 2 }).format(num)
}

function formatDate(value: string) {
  if (!value) return '-'
  return new Date(value).toLocaleDateString('zh-CN')
}

function formatDateTime(value: string) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN')
}

// 导出CSV
function exportCsv() {
  if (!tableData.value.length) return
  
  const headers = ['调拨单号', '申请日期', '调拨类型', '调出仓库', '调入仓库', '单据状态', '出库状态', '入库状态', '总数量', '总金额', '经办人', '申请人']
  const rows = tableData.value.map(r => [
    r.transferNo,
    formatDate(r.applyDate),
    r.transferType,
    r.fromWarehouseName,
    r.toWarehouseName,
    r.billStatusName,
    r.outStatusName,
    r.inStatusName,
    r.totalQty,
    r.totalAmount,
    r.handlerName,
    r.applicantName
  ])
  
  const csv = [headers, ...rows].map(row => 
    row.map(cell => `"${String(cell ?? '').replace(/"/g, '""')}"`).join(',')
  ).join('\n')
  
  const blob = new Blob(["\ufeff" + csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `调拨查询_${Date.now()}.csv`
  a.click()
  URL.revokeObjectURL(url)
}

// 事件处理
function handleSearch() {
  query.PageIndex = 1
  fetchList()
}

function handleReset() {
  Object.assign(query, {
    PageIndex: 1,
    PageSize: 10,
    TransferNo: '',
    FromWarehouseId: undefined,
    ToWarehouseId: undefined,
    BillStatus: undefined,
    OutStatus: undefined,
    InStatus: undefined,
    BeginDate: '',
    EndDate: ''
  })
  fetchList()
}

function handleCurrentChange(page: number) {
  query.PageIndex = page
  fetchList()
}

function handleSizeChange(size: number) {
  query.PageSize = size
  query.PageIndex = 1
  fetchList()
}

function openDetail(row: TransferItem) {
  router.push({ name: 'TransferDetail', params: { id: row.transferId } })
}

function handleAdd() {
  router.push({ name: 'TransferAdd' })
}

onMounted(async () => {
  await fetchWarehouses()
  await fetchList()
})
</script>

<style scoped>
.page-wrap {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-tag {
  vertical-align: middle;
}

.page-actions {
  display: flex;
  gap: 8px;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.stat-card {
  text-align: center;
}

.stat-title {
  color: #6b7280;
  font-size: 12px;
}

.stat-value {
  font-size: 20px;
  font-weight: 700;
  margin-top: 4px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
